import { createRouter, createWebHistory } from "vue-router"
import type { RouteRecordRaw } from "vue-router"
import localCache from "@/utils/localCache"
import NProgress from "@/config"
import "nprogress/nprogress.css" // progress bar style
import useLoginStore from "@/store/login"
import useGlobeStore from "@/store/globe"
import { initialRouter } from "./initialRouter"

const routes: RouteRecordRaw[] = [
	{
		path: "/",
		redirect: "/main"
	},
	{
		path: "/login",
		name: "login",
		component: () => import("@/views/login/index.vue")
	},
	{
		path: "/main",
		name: "main",
		redirect: "/main/home/index",
		component: () => import("@/layout/index.vue"),
		children: [
			{
				path: "/main/profile",
				name: "profile",
				component: () => import("@/views/main/Profile/Profile.vue")
			}
		]
	},
	// {
	// 	path: "/:pathMatch(.*)",
	// 	name: "notfond",
	// 	component: () => import("@/views/notfond/index.vue")
	// }
	{
		path: "/404",
		name: "404",
		component: () => import("@/views/notfond/index.vue")
	}
]

const router = createRouter({
	history: createWebHistory(),
	routes,
	scrollBehavior: () => ({ left: 0, top: 0 })
})

const staticRouter = ["/", "/login", "/404", "/main/profile", "/main"]
router.beforeEach((to, _from) => {
	// debugger
	document.title = (to.meta.title as string) ?? "后台管理系统"
	NProgress.start()
	const loginStore = useLoginStore()
	const globeStore = useGlobeStore()
	const token = loginStore.token ?? localCache.getCache("login", false).token
	if (to.path !== "/login") {
		if (!token) {
			return "/login"
		}
	}

	if (router.getRoutes().length === staticRouter.length && loginStore.menuList.length) {
		initialRouter(loginStore.menuList)
		router.addRoute({
			path: "/:pathMatch(.*)",
			redirect: "/404"
		})
		Promise.all([
			globeStore.getPageListMenuAction(),
			globeStore.getPageListRoleAction(),
			globeStore.getPageListDepartmentAction()
		])
		return to.path
	}

	// if (to.path === '/main') {
	// 	console.log('firstMenu', firstMenu.url)
	// 	return firstMenu.url
	// }

	// NProgress.done()
})

/**
 * @description 路由跳转结束
 * */
router.afterEach(() => {
	NProgress.done()
})

export default router
